package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.IntegralEnum;
import com.atguigu.srb.core.mapper.BorrowerAttachMapper;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.mapper.UserIntegralMapper;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.BorrowerAttach;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.entity.UserIntegral;
import com.atguigu.srb.core.pojo.vo.BorrowerApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerAttachVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.vo.BorrowerVO;
import com.atguigu.srb.core.service.BorrowerAttachService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Mr.bilal
 * @since 2023-07-18
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    BorrowerAttachMapper borrowerAttachMapper;

    @Autowired
    BorrowerAttachService borrowerAttachService;

    @Autowired
    DictService dictService;

    @Resource
    UserIntegralMapper userIntegralMapper;

    @Override
    public Integer getBorrowerStatusByUserId(String userId) {
        QueryWrapper<Borrower> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        Borrower borrower = baseMapper.selectOne(queryWrapper);
        if (borrower == null) {
            return 0;
        }
        return borrower.getStatus();
    }

    @Override
    public void saveBorrower(BorrowerVO borrowerVO, String userId) {
        // 保存borrower
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO,borrower);
        borrower.setUserId(Long.valueOf(userId));

        UserInfo userInfo = userInfoMapper.selectById(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);
        // 返回borrower主键id
        Long borrowerId = borrower.getId();

//        // 根据主键id保存attach集合
        List<BorrowerAttach> attachList = borrowerVO.getBorrowerAttachList();
//        for (BorrowerAttach borrowerAttach: attachList) {
//            borrowerAttach.setBorrowerId(borrowerId);
//            borrowerAttachMapper.insert(borrowerAttach);
//        }

        List<BorrowerAttach> newAttachList = new ArrayList<>();
        for (BorrowerAttach borrowerAttach : attachList) {
            borrowerAttach.setBorrowerId(borrowerId);
            newAttachList.add(borrowerAttach);
        }
        if (!newAttachList.isEmpty()) {
            borrowerAttachService.saveBatch(newAttachList);
        }
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public IPage<Borrower> getListPage(IPage<Borrower> borrowerPage, String keyword) {
        QueryWrapper<Borrower> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)){
            queryWrapper.like("name",keyword)
                    .or().like("mobile",keyword)
                    .or().like("id_card",keyword);
        }
        IPage<Borrower> borrowerIPage = baseMapper.selectPage(borrowerPage, queryWrapper);
        return borrowerIPage;
    }

    @Override
    public BorrowerDetailVO show(Long borrowerId) {

        // 封装borrower
        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();
        Borrower borrower = baseMapper.selectById(borrowerId);
        BeanUtils.copyProperties(borrower,borrowerDetailVO);
        borrowerDetailVO.setSex(borrower.getSex()==0?"女":"男");
        borrowerDetailVO.setMarry(borrower.getMarry()?"已婚":"否");
        borrowerDetailVO.setStatus(BorrowerStatusEnum.getMsgByStatus(borrower.getStatus()));
        borrowerDetailVO.setEducation(dictService.getDictNameByDictCodeAndValueId("education",borrower.getEducation()));//学历
        borrowerDetailVO.setReturnSource(dictService.getDictNameByDictCodeAndValueId("returnSource",borrower.getReturnSource()));
        borrowerDetailVO.setIndustry(dictService.getDictNameByDictCodeAndValueId("industry",borrower.getIndustry()));
        borrowerDetailVO.setContactsRelation(dictService.getDictNameByDictCodeAndValueId("relation",borrower.getContactsRelation()));
        borrowerDetailVO.setIncome(dictService.getDictNameByDictCodeAndValueId("income",borrower.getIncome()));
        // 封装图片集合
        QueryWrapper<BorrowerAttach> attachQueryWrapper = new QueryWrapper<>();
        attachQueryWrapper.eq("borrower_id",borrowerId);
        List<BorrowerAttach> attachList = borrowerAttachMapper.selectList(attachQueryWrapper);
        List<BorrowerAttachVO> borrowerAttachVOList = attachList.stream().map(borrowerAttach -> {
            BorrowerAttachVO borrowerAttachVO = new BorrowerAttachVO();
            BeanUtils.copyProperties(borrowerAttach,borrowerAttachVO);
            return borrowerAttachVO;
        }).collect(Collectors.toList());
        borrowerDetailVO.setBorrowerAttachVOList(borrowerAttachVOList);

        return borrowerDetailVO;
    }

    @Override
    public void approvalSubmit(BorrowerApprovalVO borrowerApprovalVO) {
        // 修改borrower状态
        Integer status = borrowerApprovalVO.getStatus();
        Borrower borrower = baseMapper.selectById(borrowerApprovalVO.getBorrowerId());
        borrower.setStatus(status);
        baseMapper.updateById(borrower);

        //计算总积分用的
        BigDecimal sum = new BigDecimal("0");
        // 新增user_integral
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setIntegral(borrowerApprovalVO.getInfoIntegral());
        userIntegral.setUserId(borrower.getUserId());
        userIntegral.setContent("基本信息积分");
        userIntegralMapper.insert(userIntegral);
        sum = sum.add(new BigDecimal(borrowerApprovalVO.getInfoIntegral()));

        if (borrowerApprovalVO.getIsIdCardOk()) {
            UserIntegral userIntegralIdCar = new UserIntegral();
            userIntegralIdCar.setUserId(borrower.getUserId());
            userIntegralIdCar.setContent("身份证积分");
            userIntegralIdCar.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegralMapper.insert(userIntegralIdCar);
            sum = sum.add(new BigDecimal(IntegralEnum.BORROWER_IDCARD.getIntegral()));
        }

        if (borrowerApprovalVO.getIsHouseOk()) {
            UserIntegral userIntegralHouse = new UserIntegral();
            userIntegralHouse.setUserId(borrower.getUserId());
            userIntegralHouse.setContent("房产积分");
            userIntegralHouse.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegralMapper.insert(userIntegralHouse);
            sum = sum.add(new BigDecimal(IntegralEnum.BORROWER_HOUSE.getIntegral()));
        }

        if(borrowerApprovalVO.getIsCarOk()) {
            UserIntegral carUserIntegral = new UserIntegral();
            carUserIntegral.setUserId(borrower.getUserId());
            carUserIntegral.setContent("车子积分");
            carUserIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegralMapper.insert(carUserIntegral);
            sum = sum.add(new BigDecimal(IntegralEnum.BORROWER_CAR.getIntegral()));

        }

        // 修改user_info,借款人状态，总积分
        UserInfo userInfo = userInfoMapper.selectById(borrower.getUserId());
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_OK.getStatus());
        userInfo.setIntegral(sum.intValue());
        userInfoMapper.updateById(userInfo);
    }
}
